package com.example.chapter06;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

import com.example.chapter06.dao.BookDao;
import com.example.chapter06.entity.BookInfo;
import com.example.chapter06.util.ToastUtil;

import java.util.List;

public class RoomWriteActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText et_name, et_author, et_press, et_price;
    private BookDao bookDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_room_write);

        et_name = findViewById(R.id.et_name);
        et_author = findViewById(R.id.et_author);
        et_press = findViewById(R.id.et_press);
        et_price = findViewById(R.id.et_price);

        findViewById(R.id.btn_add).setOnClickListener(this);
        findViewById(R.id.btn_delete).setOnClickListener(this);
        findViewById(R.id.btn_update).setOnClickListener(this);
        findViewById(R.id.btn_query).setOnClickListener(this);

        // 从App实例中获取唯一的书籍持久化对象
        bookDao = MyApplication.getInstance().getBookDB().bookDao();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_add) {
            BookInfo b1 = new BookInfo();
            b1.setName(et_name.getText().toString());
            b1.setAuthor(et_author.getText().toString());
            b1.setPress(et_press.getText().toString());
            b1.setPrice(Double.parseDouble(et_price.getText().toString()));
            bookDao.insert(b1);
            ToastUtil.show(this, "保存成功");
        } else if (v.getId() == R.id.btn_delete) {
            BookInfo b2 = new BookInfo();
            BookInfo b_exists = bookDao.queryByName(et_name.getText().toString());
            b2.setId(b_exists.getId());
            b2.setName(et_name.getText().toString());
            bookDao.delete(b2);
            ToastUtil.show(this, "删除成功");
        } else if (v.getId() == R.id.btn_update) {
            BookInfo b3 = new BookInfo();
            // 修改时，必须指定主键，否则无法更新
            BookInfo b4 = bookDao.queryByName(et_name.getText().toString());
            b3.setId(b4.getId());
            b3.setName(et_name.getText().toString());
            b3.setAuthor(et_author.getText().toString());
            b3.setPress(et_press.getText().toString());
            b3.setPrice(Double.parseDouble(et_price.getText().toString()));
            bookDao.update(b3);
            ToastUtil.show(this, "更新成功");
        } else if (v.getId() == R.id.btn_query) {
            List<BookInfo> bookInfoList = bookDao.queryAll();
            for (BookInfo bookInfo : bookInfoList) {
                Log.d("RoomWriteActivity", bookInfo.toString());
            }
        }
    }
}